"""
智能决策工具
将智能决策引擎集成到MCP工具系统中
"""

import json
import logging
from typing import Dict, List, Any, Optional
from datetime import datetime
import asyncio

from .registry import register_tool
from ..features.intelligent_decision_engine import (
    IntelligentDecisionEngine, LLMInferenceResult, ExecutionPlan
)

logger = logging.getLogger(__name__)

# 全局智能决策引擎
_decision_engine: Optional[IntelligentDecisionEngine] = None

def _get_decision_engine() -> IntelligentDecisionEngine:
    """获取智能决策引擎实例"""
    global _decision_engine
    
    if _decision_engine is None:
        _decision_engine = IntelligentDecisionEngine()
        logger.info("智能决策引擎初始化完成")
    
    return _decision_engine

async def process_llm_inference_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """处理LLM推理结果并生成执行计划"""
    try:
        # 获取LLM推理数据
        llm_data = arguments.get("llm_data", {})
        
        if not llm_data:
            return [{"text": "❌ 缺少LLM推理数据"}]
        
        # 获取决策引擎并处理
        engine = _get_decision_engine()
        plan = await engine.process_llm_inference(llm_data)
        
        # 转换为可序列化的格式
        plan_data = {
            "plan_id": plan.plan_id,
            "problem_type": plan.llm_result.problem_type,
            "severity": plan.llm_result.severity,
            "description": plan.llm_result.description,
            "risk_level": plan.risk_level,
            "estimated_total_time": plan.estimated_total_time,
            "tasks_count": len(plan.tasks),
            "tasks": [
                {
                    "task_id": task.task_id,
                    "agent_type": task.agent_type.value,
                    "priority": task.priority.value,
                    "description": task.description,
                    "estimated_duration": task.estimated_duration
                }
                for task in plan.tasks
            ],
            "execution_order": plan.execution_order,
            "created_at": plan.created_at.isoformat()
        }
        
        logger.info(f"生成执行计划: {plan.plan_id}")
        return [{"text": json.dumps(plan_data, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"处理LLM推理失败: {e}")
        return [{"text": f"❌ 处理LLM推理失败: {str(e)}"}]

async def execute_plan_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """执行指定的计划"""
    try:
        plan_id = arguments.get("plan_id")
        
        if not plan_id:
            return [{"text": "❌ 缺少计划ID"}]
        
        # 获取决策引擎
        engine = _get_decision_engine()
        
        # 查找计划
        plan = None
        for p in engine.execution_history:
            if p.plan_id == plan_id:
                plan = p
                break
        
        if not plan:
            return [{"text": f"❌ 未找到计划: {plan_id}"}]
        
        # 执行计划
        logger.info(f"开始执行计划: {plan_id}")
        result = await engine.execute_plan(plan)
        
        logger.info(f"计划执行完成: {plan_id} - 状态: {result['status']}")
        return [{"text": json.dumps(result, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"执行计划失败: {e}")
        return [{"text": f"❌ 执行计划失败: {str(e)}"}]

async def auto_process_and_execute_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """自动处理LLM推理并执行计划"""
    try:
        # 获取LLM推理数据 - 支持新的数据格式
        llm_data = arguments.get("llm_data", {})
        analysis_result = arguments.get("analysis_result", {})
        
        # 如果提供了analysis_result，则使用新的数据格式
        if analysis_result:
            logger.info("检测到新的LLM数据格式 (analysis_result)")
            # 从analysis_result中提取数据
            overall_assessment = analysis_result.get("overall_assessment", {})
            recommendations = analysis_result.get("recommendations", {})
            
            # 转换为兼容的llm_data格式
            llm_data = {
                "problem_type": overall_assessment.get("primary_issue", "unknown"),
                "severity": overall_assessment.get("severity_level", 5.0),
                "description": overall_assessment.get("root_cause", ""),
                "affected_services": analysis_result.get("affected_services_summary", {}).get("primary_affected", []),
                "suggested_actions": [
                    action.get("description", "") 
                    for action in recommendations.get("immediate_actions", [])
                ],
                "confidence": overall_assessment.get("confidence_score", 0.8),
                "reasoning": "LLM+RAG+Langraph分析结果",
                "timestamp": analysis_result.get("analysis_timestamp", datetime.now().isoformat()),
                # 新增字段
                "business_impact": overall_assessment.get("business_impact", "unknown"),
                "estimated_resolution_time": overall_assessment.get("estimated_resolution_time", "unknown"),
                "anomaly_analysis": analysis_result.get("anomaly_analysis", []),
                "langraph_workflow": analysis_result.get("langraph_workflow", {})
            }
        
        if not llm_data:
            return [{"text": "❌ 缺少LLM推理数据"}]
        
        # 获取决策引擎
        engine = _get_decision_engine()
        
        # 1. 处理LLM推理并生成计划
        logger.info("开始自动处理LLM推理")
        plan = await engine.process_llm_inference(llm_data)
        
        # 2. 执行计划
        logger.info(f"开始执行计划: {plan.plan_id}")
        execution_result = await engine.execute_plan(plan)
        
        # 3. 合并结果
        final_result = {
            "plan_id": plan.plan_id,
            "status": execution_result.get("status", "unknown"),
            "execution_time": 0.0,  # 可以计算实际执行时间
            "plan_generation": {
                "plan_id": plan.plan_id,
                "problem_type": plan.llm_result.problem_type,
                "severity": plan.llm_result.severity,
                "risk_level": plan.risk_level,
                "tasks_count": len(plan.tasks)
            },
            "execution": execution_result,
            "generated_scripts": [],  # 可以从execution_result中提取
            "deployment_status": "pending"  # 部署状态
        }
        
        # 提取生成的脚本
        if "task_results" in execution_result:
            for task_result in execution_result["task_results"].values():
                if "generated_scripts" in task_result:
                    final_result["generated_scripts"].extend(task_result["generated_scripts"])
        
        logger.info(f"自动处理完成: {plan.plan_id}")
        return [{"text": json.dumps(final_result, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"自动处理失败: {e}")
        return [{"text": f"❌ 自动处理失败: {str(e)}"}]

async def get_execution_history_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """获取执行历史"""
    try:
        limit = arguments.get("limit", 10)
        
        # 从MySQL数据库获取执行历史
        from ..db.mysql_persistence import get_execution_plans_from_mysql
        history_data = get_execution_plans_from_mysql(limit)
        
        # 转换为简化的格式用于显示
        simplified_history = []
        for plan in history_data:
            # 调试输出每个字段的类型
            print(f"\n[DEBUG] plan_id={plan['plan_id']}")
            for k, v in plan.items():
                print(f"  {k}: {type(v)} -> {v}")
            plan_info = {
                "plan_id": plan["plan_id"],
                "problem_type": plan["problem_type"],
                "severity": plan["severity"],
                "risk_level": plan["risk_level"],
                "tasks_count": len(plan["tasks"]) if plan["tasks"] else 0,
                "estimated_total_time": plan["estimated_total_time"],
                "created_at": str(plan["created_at"]) if plan["created_at"] else None
            }
            simplified_history.append(plan_info)
        
        logger.info(f"从MySQL获取执行历史: {len(simplified_history)} 条记录")
        return [{"text": json.dumps(simplified_history, ensure_ascii=False, indent=2, default=str)}]
        
    except Exception as e:
        logger.error(f"获取执行历史失败: {e}")
        return [{"text": f"❌ 获取执行历史失败: {str(e)}"}]

async def analyze_problem_pattern_impl(arguments: Dict[str, Any]) -> List[Dict[str, Any]]:
    """分析问题模式"""
    try:
        # 获取决策引擎
        engine = _get_decision_engine()
        history = engine.get_execution_history(100)  # 获取更多历史数据
        
        if not history:
            return [{"text": "暂无执行历史数据"}]
        
        # 分析问题类型分布
        problem_types = {}
        severity_distribution = {"low": 0, "medium": 0, "high": 0, "critical": 0}
        agent_usage = {}
        
        for plan in history:
            # 问题类型统计
            problem_type = plan.llm_result.problem_type
            problem_types[problem_type] = problem_types.get(problem_type, 0) + 1
            
            # 严重程度分布
            severity = plan.llm_result.severity
            if severity >= 8.0:
                severity_distribution["critical"] += 1
            elif severity >= 6.0:
                severity_distribution["high"] += 1
            elif severity >= 4.0:
                severity_distribution["medium"] += 1
            else:
                severity_distribution["low"] += 1
            
            # Agent使用统计
            for task in plan.tasks:
                agent_type = task.agent_type.value
                agent_usage[agent_type] = agent_usage.get(agent_type, 0) + 1
        
        # 生成分析报告
        analysis = {
            "total_plans": len(history),
            "problem_type_distribution": problem_types,
            "severity_distribution": severity_distribution,
            "agent_usage_statistics": agent_usage,
            "most_common_problem": max(problem_types.items(), key=lambda x: x[1])[0] if problem_types else "unknown",
            "average_severity": sum(p.llm_result.severity for p in history) / len(history),
            "analysis_time": datetime.now().isoformat()
        }
        
        logger.info("问题模式分析完成")
        return [{"text": json.dumps(analysis, ensure_ascii=False, indent=2)}]
        
    except Exception as e:
        logger.error(f"分析问题模式失败: {e}")
        return [{"text": f"❌ 分析问题模式失败: {str(e)}"}]

# 注册工具
register_tool(
    "process_llm_inference",
    "处理LLM推理结果并生成智能执行计划",
    {
        "type": "object",
        "properties": {
            "llm_data": {
                "type": "object",
                "description": "LLM推理结果数据",
                "properties": {
                    "problem_type": {"type": "string", "description": "问题类型"},
                    "severity": {"type": "number", "description": "严重程度 (0-10)"},
                    "description": {"type": "string", "description": "问题描述"},
                    "affected_services": {"type": "array", "items": {"type": "string"}, "description": "受影响的服务"},
                    "suggested_actions": {"type": "array", "items": {"type": "string"}, "description": "建议的操作"},
                    "confidence": {"type": "number", "description": "置信度"},
                    "reasoning": {"type": "string", "description": "推理过程"},
                    "timestamp": {"type": "string", "description": "时间戳"}
                },
                "required": ["problem_type", "severity", "description"]
            }
        },
        "required": ["llm_data"]
    },
    process_llm_inference_impl
)

register_tool(
    "execute_plan",
    "执行指定的智能执行计划",
    {
        "type": "object",
        "properties": {
            "plan_id": {
                "type": "string",
                "description": "要执行的计划ID"
            }
        },
        "required": ["plan_id"]
    },
    execute_plan_impl
)

register_tool(
    "auto_process_and_execute",
    "自动处理LLM推理并执行计划（一站式服务）",
    {
        "type": "object",
        "properties": {
            "llm_data": {
                "type": "object",
                "description": "LLM推理结果数据",
                "properties": {
                    "problem_type": {"type": "string", "description": "问题类型"},
                    "severity": {"type": "number", "description": "严重程度 (0-10)"},
                    "description": {"type": "string", "description": "问题描述"},
                    "affected_services": {"type": "array", "items": {"type": "string"}, "description": "受影响的服务"},
                    "suggested_actions": {"type": "array", "items": {"type": "string"}, "description": "建议的操作"},
                    "confidence": {"type": "number", "description": "置信度"},
                    "reasoning": {"type": "string", "description": "推理过程"},
                    "timestamp": {"type": "string", "description": "时间戳"}
                },
                "required": ["problem_type", "severity", "description"]
            }
        },
        "required": ["llm_data"]
    },
    auto_process_and_execute_impl
)

register_tool(
    "get_execution_history",
    "获取智能决策执行历史",
    {
        "type": "object",
        "properties": {
            "limit": {
                "type": "integer",
                "description": "返回的历史记录数量限制",
                "default": 10
            }
        }
    },
    get_execution_history_impl
)

register_tool(
    "analyze_problem_pattern",
    "分析问题模式和执行趋势",
    {
        "type": "object",
        "properties": {}
    },
    analyze_problem_pattern_impl
) 